<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">同步任务管理</h1>
      <p class="page-subtitle">管理和监控数据同步任务</p>
    </div>

    <div class="action-bar">
      <div class="action-left">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索任务名称"
          style="width: 300px"
          clearable
        >
          <template #prefix>
            🔍
          </template>
        </el-input>
        <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 120px" clearable>
          <el-option label="全部" value="" />
          <el-option label="运行中" value="running" />
          <el-option label="已停止" value="stopped" />
          <el-option label="成功" value="success" />
          <el-option label="失败" value="failed" />
        </el-select>
      </div>
      <div class="action-right">
        <el-button type="primary" @click="handleCreate">
          ➕ 新增任务
        </el-button>
      </div>
    </div>

    <div class="page-content">
      <el-table :data="filteredTasks" v-loading="loading" style="width: 100%">
        <el-table-column prop="name" label="任务名称" min-width="180" />
        <el-table-column prop="source_name" label="源数据源" min-width="120" />
        <el-table-column prop="target_name" label="目标数据源" min-width="120" />
        <el-table-column prop="sync_type" label="同步类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.sync_type === 'full' ? 'primary' : 'success'">
              {{ row.sync_type === 'full' ? '全量同步' : '增量同步' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="last_sync_time" label="最近同步时间" width="180" />
        <el-table-column prop="sync_frequency" label="同步频率" width="120" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.status !== 'running'" 
              type="success" 
              link 
              @click="handleStart(row)"
            >
              启动
            </el-button>
            <el-button 
              v-if="row.status === 'running'" 
              type="warning" 
              link 
              @click="handleStop(row)"
            >
              停止
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="info" link @click="handleViewLog(row)">日志</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getTaskList, deleteTask, startTask, stopTask } from '@/api/task'

const router = useRouter()
const loading = ref(false)
const searchKeyword = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 任务数据
const tasks = ref([])

// 过滤后的任务（现在由后端处理分页和筛选）
const filteredTasks = computed(() => {
  return tasks.value
})

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'running': 'primary',
    'success': 'success',
    'failed': 'danger',
    'stopped': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'running': '运行中',
    'success': '成功',
    'failed': '失败',
    'stopped': '已停止'
  }
  return statusMap[status] || '未知'
}

// 处理新增
const handleCreate = () => {
  router.push('/task/create')
}

// 处理编辑
const handleEdit = (row) => {
  router.push(`/task/edit/${row.id}`)
}

// 处理查看日志
const handleViewLog = (row) => {
  router.push(`/task/log/${row.id}`)
}

// 处理启动任务
const handleStart = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要启动任务 "${row.name}" 吗？`,
      '确认启动',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    loading.value = true
    const res = await startTask(row.id)
    
    if (res.code === 200) {
      ElMessage.success('任务启动成功')
      // 重新获取数据以更新状态
      await fetchData()
    } else {
      ElMessage.error(res.message || '启动任务失败')
    }
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message !== 'cancel') {
      ElMessage.error('启动任务失败')
    }
  } finally {
    loading.value = false
  }
}

// 处理停止任务
const handleStop = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要停止任务 "${row.name}" 吗？`,
      '确认停止',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    const res = await stopTask(row.id)
    
    if (res.code === 200) {
      ElMessage.success('任务停止成功')
      // 重新获取数据以更新状态
      await fetchData()
    } else {
      ElMessage.error(res.message || '停止任务失败')
    }
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message !== 'cancel') {
      ElMessage.error('停止任务失败')
    }
  } finally {
    loading.value = false
  }
}

// 处理删除
const handleDelete = async (row) => {
  if (row.status === 'running') {
    ElMessage.warning('请先停止任务再删除')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除任务 "${row.name}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await deleteTask(row.id)
    
    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 重新获取数据
      await fetchData()
    } else {
      ElMessage.error(res.message || '删除任务失败')
    }
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message !== 'cancel') {
      ElMessage.error('删除任务失败')
    }
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchData()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getTaskList({
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value,
      status: statusFilter.value
    })
    
    if (res.code === 200) {
      tasks.value = res.data || []
      total.value = res.total || 0
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('获取数据失败')
    }
    tasks.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 监听搜索和筛选变化
watch([searchKeyword, statusFilter], () => {
  currentPage.value = 1
  fetchData()
})

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>